package com.example.cachedemo.controller;

import com.example.cachedemo.service.CheckService;
import com.example.cachedemo.service.dto.check.ClassCheckAbsentDTO;
import org.springframework.cache.CacheManager;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class CheckAbsentController {
    private final CheckService checkService;

    public CheckAbsentController(CheckService checkService, CacheManager cacheManager) {
        this.checkService = checkService;
    }

    //http://localhost:8080/api/check/class-absent?className=移动1923&termNo=20200
    //不使用缓存
    @GetMapping("/check/class-absent")
    public ResponseEntity getClassCheckAbsent(String className, String termNo) {
        long time0 = System.currentTimeMillis();
        ClassCheckAbsentDTO result = this.checkService.getClassCheckAbsent(className, termNo);
        long time1 = System.currentTimeMillis();
        result.setTotalTime(time1 - time0);
        return ResponseEntity.ok(result);
    }

    //使用自定义简易缓存对象
    /*@GetMapping("/check/class-absent")
    public ResponseEntity getClassCheckAbsent(String className,String termNo){
        long time0 = System.currentTimeMillis();
        ClassCheckAbsentDTO result=null;
        //将参数构造成缓存的key
        //1.根据cache的key到缓存进行查询
        String cachekey=className+"-"+termNo;
        //通过缓存工具获取已经缓存的结果
        Object cacheObject= SimpleCache.getCache(cachekey);
        //2.根据缓存查询的结果是否为null，进行不同的处理
        // 如果命中缓存
        if (cacheObject!=null){
            //2.1不为空
            result=(ClassCheckRatioDTO) cacheObject;
        }else {
            //2.2为空，去数据库查询，并同时将查询结果放到缓存中  未命中就调用服务查询
            result=this.checkService.getClassCheckRatio(className,termNo);
            //查询后将结果缓存
            SimpleCache.setCache(cachekey,result);
        }
        long time1=System.currentTimeMillis();
        result.setTotalTime(time1-time0);
        return ResponseEntity.ok(result);
    }*/
}